package parsers;

import helpers.CacheHelper;
import helpers.ParsingHelper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import datamodel.Entry;
import datamodel.PossibleMatch;

public class ImdbParser implements ParserCommand {
	public boolean isParseable( Entry entry ) {
		// IMDB has TV shows but this can't process them right now
		return !entry.isTVShow();
	}

	public void executeSearchParsing( Entry entry ) throws Exception {
		StringBuffer buffer = CacheHelper.getCachedFile( "http://www.imdb.com/find?s=all&q=" + entry.getTitle() );

		int popularTitlesIndex = buffer.indexOf( "<p><b>Popular Titles</b>" );
		int exactTitlesIndex = buffer.indexOf( "<p><b>Titles (Exact Matches)</b>" );

		if ( popularTitlesIndex != -1 || exactTitlesIndex != -1 ) {
			// Handle regular searches
			StringBuilder popularTitles;

			if ( popularTitlesIndex != -1 ) {
				popularTitles = ParsingHelper.parseBetween( buffer, "<p><b>Popular Titles</b>", "</table>" );
			} else {
				popularTitles = ParsingHelper.parseBetween( buffer, "<p><b>Titles (Exact Matches)</b>", "</table>" );
			}

			Pattern hitPattern = Pattern.compile( "<a href=\"/title/(\\w*)/\">(.*?)</a> \\((\\d*)(.*?)\\)" );
			Matcher m = hitPattern.matcher( popularTitles );

			PossibleMatch possibleMatch = new PossibleMatch();

			while ( m.find() ) {
				possibleMatch.addMatch( m.group( 2 ) + " " + m.group( 3 ), "http://www.imdb.com/title/" + m.group( 1 ) );
			}

			entry.setPossibleMatch( possibleMatch );
		} else {
			// Handle when IMDB gets a direct hit, it redirects to the page

			// Get the inetref when there is a direct hit and set so that it can
			// be parsed
			Pattern pattern = Pattern.compile( "/title/tt(\\d*)/fullcredits" );
			Matcher matcher = pattern.matcher( buffer );

			if ( matcher.find() == true ) {
				entry.setInetref( matcher.group( 0 ) );
			}

			processFinalParsing( entry, buffer );
		}
	}

	public void executeFinalParsing( Entry entry ) throws Exception {

		StringBuffer buffer = CacheHelper.getCachedFile( entry.getInetref() );

		processFinalParsing( entry, buffer );
	}

	private void processFinalParsing( Entry entry, StringBuffer buffer ) {
		String title = ParsingHelper.findGroup( "<h1>(.*)<span>(.*)</h1>", buffer, 1 );
		title = title.trim();

		String director = ParsingHelper.findGroup( "Director[s]?:(.*)\\n(.*)/\">(.*)</a>", buffer, 3 );

		// TODO: My regex skills failed me here, need to do with regex only 
		String plot;
		if ( buffer.indexOf( "<a class" ) != -1 ) {
			plot = ParsingHelper.findGroup( "Plot (Outline|Summary):(.*)\\n(.*)<a class", buffer, 3 );
		} else {
			plot = ParsingHelper.findGroup( "Plot (Outline|Summary):(.*)\\n(.*)", buffer, 3 );
		}
		
		String rating = ParsingHelper.findGroup( "Certification:(.*)\\n(.*)\">USA:([a-zA-Z_0-9-]*)</a>", buffer, 3 );
		String year = ParsingHelper.findGroup( "<div id=\"tn15title\">\\n(.*)\">(\\d*)</a>", buffer, 2 );
		String userRating = ParsingHelper.findGroup( "<b>User Rating:</b>(.*)\\n<b>(\\d\\.\\d)", buffer, 2 );
		String length = ParsingHelper.findGroup( "Runtime:(.*)\\n(\\w*:)?(\\d*) min", buffer, 3 );

		entry.setTitle( title );
		entry.setDirector( director );
		entry.setPlot( plot );
		entry.setRating( rating );
		entry.setYear( year );
		entry.setUserrating( userRating );
		entry.setLength( length );

		entry.setInetref( ParsingHelper.findGroup( "/title/tt(\\d*)", entry.getInetref(), 1 ) );

		entry.setProcessed( true );
	}
}
